<script setup lang="tsx">
import { h, onMounted, ref } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { useAppStore } from '@/store/modules/app';
import { useAuth } from '@/hooks/business/auth';
import type { SmsTemplate } from '@/service/api';
import { deleteSmsTemplate, fetchSmsChannelOptions, fetchSmsTemplateList, getFetchSmsTemplateUrl } from '@/service/api';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { DICT_TYPE, getDictObj } from '@/utils/dict';
import { useBoolean } from '~/packages/hooks/src';
import SmsTemplateSearch from './modules/sms-template-search.vue';
import SmsTemplateOperateModal from './modules/sms-template-operate-modal.vue';
import SmsTemplateSendModal from './modules/sms-template-send-modal.vue';

const wrapperRef = ref<HTMLElement | null>(null);
const appStore = useAppStore();
const { hasAuth } = useAuth();

const { bool: smsTemplateSendVisible, setTrue: openSmsTemplateSendModal } = useBoolean();

const channelList = ref<CommonType.OptionExtra<number>[] | null>([]); // 短信渠道列表

const rowDataSmsTemplate = ref<SmsTemplate>();

const {
  columns,
  columnChecks,
  data,
  loading,
  mobilePagination,
  getData,
  getDataByPage,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchSmsTemplateList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    type: null,
    status: null,
    code: null,
    apiTemplateId: null,
    channelId: null,
    createTime: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'code',
      title: $t('page.base.sms.template.code'),
      align: 'center',
      width: 140,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'name',
      title: $t('page.base.sms.template.name'),
      align: 'center',
      width: 120,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'content',
      title: $t('page.base.sms.template.content'),
      align: 'center',
      width: 300,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'type',
      title: $t('page.base.sms.template.type'),
      align: 'center',
      width: 80,
      ellipsis: {
        tooltip: true
      },
      render: row => {
        if (row.type === null) {
          return '~';
        }
        const dictObj = getDictObj(DICT_TYPE.SYSTEM_SMS_TEMPLATE_TYPE, row.type);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'status',
      title: $t('page.base.sms.template.status'),
      align: 'center',
      width: 80,
      ellipsis: {
        tooltip: true
      },
      render: row => {
        if (row.status === null) {
          return null;
        }
        const dictObj = getDictObj(DICT_TYPE.COMMON_STATUS, row.status);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'remark',
      title: $t('page.base.sms.template.remark'),
      align: 'center',
      width: 150,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'apiTemplateId',
      title: $t('page.base.sms.template.apiTemplateId'),
      align: 'center',
      width: 100,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'channelCode',
      title: $t('page.base.sms.template.channel'),
      align: 'center',
      width: 100,
      ellipsis: {
        tooltip: true
      },
      render: row => {
        if (row.channelCode === null) {
          return null;
        }
        const dictObj = getDictObj(DICT_TYPE.SYSTEM_SMS_CHANNEL_CODE, row.channelCode);

        return (
          <div>
            {channelList.value?.find(channel => channel.value === row.channelId)?.extra}
            <NTag type={dictObj?.colorType} class="ml-2">
              {dictObj?.label}
            </NTag>
          </div>
        );
      }
    },
    {
      key: 'createTime',
      title: $t('page.base.sms.template.createTime'),
      align: 'center',
      width: 120
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 180,
      render: row => (
        <div class="flex-center gap-8px">
          <div v-show={hasAuth('system:sms-template:update')}>
            <NButton type="primary" ghost size="small" disabled={row.id === 0} onClick={() => edit(row.id)}>
              {{
                default: () => $t('common.edit'),
                icon: () => h(SvgIcon, { icon: 'ep:edit' })
              }}
            </NButton>
          </div>
          <div v-show={hasAuth('system:sms-template:send-sms')}>
            <NButton type="primary" ghost size="small" disabled={row.id === 0} onClick={() => handleSendSms(row)}>
              {{
                default: () => $t('common.test'),
                icon: () => h(SvgIcon, { icon: 'ep:promotion' })
              }}
            </NButton>
          </div>
          <div v-show={hasAuth('system:sms-template:delete')}>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" ghost size="small" disabled={row.id === 0}>
                    {{
                      default: () => $t('common.delete'),
                      icon: () => h(SvgIcon, { icon: 'ep:delete' })
                    }}
                  </NButton>
                )
              }}
            </NPopconfirm>
          </div>
        </div>
      )
    }
  ]
});

const { modelVisible, handleAdd, handleEdit, checkedRowKeys, onDeleted, editingData, fetchDataUrl, operateType } =
  useTableOperate(data, getData);

async function handleDelete(id: number) {
  // request
  const { error } = await deleteSmsTemplate(id.toString());
  await onDeleted(error);
}

function edit(id: number) {
  fetchDataUrl.value = getFetchSmsTemplateUrl(id);
  handleEdit(id);
}

function handleSendSms(row: SmsTemplate) {
  rowDataSmsTemplate.value = row;
  openSmsTemplateSendModal();
}

onMounted(async () => {
  // 加载渠道列表
  const { data: res } = await fetchSmsChannelOptions();
  channelList.value = res;
});
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <SmsTemplateSearch
      v-if="hasAuth('system:sms-template:query')"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />

    <NCard
      :title="$t('page.base.sms.template.title')"
      :bordered="false"
      size="small"
      class="sm:flex-1-hidden card-wrapper"
    >
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          create-auth="system:sms-template:create"
          delete-auth="system:sms-template:delete"
          @add="handleAdd"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="2088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        :pagination="mobilePagination"
        class="sm:h-full"
      />
    </NCard>

    <SmsTemplateOperateModal
      v-model:visible="modelVisible"
      :operate-type="operateType"
      :row-data="editingData"
      @submitted="getDataByPage"
    />

    <SmsTemplateSendModal v-model:visible="smsTemplateSendVisible" :row-data="rowDataSmsTemplate" />
  </div>
</template>

<style scoped></style>
